package com.fu.service.impl;

import com.fu.config.TokenCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.stereotype.Service;

import com.fu.dao.UserMapper;
import com.fu.entity.User;
import com.fu.service.UserService;
import com.fu.utils.Constants;
import com.fu.utils.Generator;

import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @ClassName: UserServiceImpl
 * @Description: 用户相关操作实现类
 * @author Little Ant
 * @date 2017年10月30日下午2:24:29
 */
@Service("userService")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;

	@Autowired
    TokenCache tokenCache;

	@Override
	public String getToken(String appId, String secretKey) {
		User user = this.userMapper.getByAppId(appId);
		if (null == user) {
			return Constants.USER_NOT_FOUND;
		}
		if (!user.getSecretKey().trim().equals(secretKey.trim())) {
			return Constants.INCORRECT_PASSWORD;
		}

		String token = Generator.generateString(30);
		if (user.getAppId() == null || "".equals(user.getAppId())) {
			user.setAppId(Generator.generateString(35));
		}
		if (user.getSecretKey() == null || "".equals(user.getSecretKey())) {
			user.setSecretKey(Generator.generateString(35));
		}
		user.setToken(token);

		this.userMapper.updateByPrimaryKeySelective(user);
		tokenCache.put(token, user.getAppId());
		return token;
	}

	@Override
	public String updateToken(String oldToken) {
		String appId = tokenCache.get(oldToken);
		User user = this.userMapper.getByAppId(appId);
		String token = Generator.generateString(30);
		user.setToken(token);
		this.userMapper.updateByPrimaryKeySelective(user);
		tokenCache.put(token,appId);
		return tokenCache.remove(oldToken);
	}
}
